//
//  CityIntroductionViewController.m
//  Funny
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 King. All rights reserved.
//

#import "CityIntroductionViewController.h"

@interface CityIntroductionViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UIScrollView *scroller;
@property (nonatomic, strong) UIImageView *headerImg;
@property (nonatomic, strong) UILabel *desc;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) MainIntroductionModel *model;
@property (nonatomic, assign) CGRect rect;
@property (nonatomic, strong) UILabel *prompt;
@property (nonatomic, strong) DataBase *dataBase;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) NSArray *dbArr;
@property (nonatomic, strong) MBProgressHUD *hub;

@end

@implementation CityIntroductionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.scroller];
    [self handleData];

    [self.scroller addSubview:self.headerImg];
    [self.scroller addSubview:self.desc];
    [self.scroller addSubview:self.prompt];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    // 背景图片
    UIImageView *backImg= [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 66)];
    [self.view addSubview:backImg];
    backImg.image = [UIImage imageNamed:@"back1.png"];
    
    // 城市名
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth / 2 - 50, 20, 100, 30)];
    name.textAlignment = NSTextAlignmentCenter;
    name.text = self.name;
    [self.scroller addSubview:name];
    
    // 返回按钮
    UIButton *backClick = [UIButton buttonWithFrame:CGRectMake(0, 23, 60, 30) color:nil title:@" 返回" type:UIButtonTypeSystem target:nil action:@selector(backToPage) event:UIControlEventTouchUpInside cornerRadius:0];
    backClick.tintColor = [UIColor whiteColor];
    [backClick setImage:[UIImage imageNamed:@"btn_back@3x.png"] forState:UIControlStateNormal];
    [self.view addSubview:backClick];
    
    // 收藏按钮
    UIButton *collectClick = [UIButton buttonWithFrame:CGRectMake(ScreenWidth - 50, 23, 35, 35) color:nil title:nil type:UIButtonTypeSystem target:self action:@selector(collectClickWithBtn:) event:UIControlEventTouchUpInside cornerRadius:0];
    [self.view addSubview:collectClick];
    
    // 进入页面时首先判断是否已收藏 已收藏显示红色 否则白色
    BOOL result = [self.dataBase open];
    if (result) {
        [self.dataBase creatTable];
    }
    self.dbArr = [self.dataBase getAll];
    if (_dbArr.count == 0) {
        [collectClick setImage:[UIImage imageNamed:@"nocollect.png"] forState:UIControlStateNormal];
        collectClick.tintColor = [UIColor whiteColor];
        _isOpen = NO;
    }
    for (MainIntroductionModel *model in _dbArr) {
        if ([model.cityID isEqualToString:self.cityID]) {
            [collectClick setImage:[UIImage imageNamed:@"collected.png"] forState:UIControlStateNormal];
            [collectClick setTintColor:[UIColor redColor]];
            _isOpen = YES;
            break;
        }
        else{
            [collectClick setImage:[UIImage imageNamed:@"nocollect.png"] forState:UIControlStateNormal];
            collectClick.tintColor = [UIColor whiteColor];
            _isOpen = NO;
        }
    }
    // Do any additional setup after loading the view.
}

- (NSArray *)dbArr{
    if (!_dbArr) {
        self.dbArr = [NSArray array];
    }
    return _dbArr;
}

// 数据库初始化 懒加载
- (DataBase *)dataBase
{
    if (!_dataBase) {
        self.dataBase = [DataBase shareDataBase];
    }
    return _dataBase;
}

#pragma mark - 数据库增减
- (void)collectClickWithBtn:(UIButton *)btn
{
    self.hub = [[MBProgressHUD alloc]initWithView:self.view];
    if (_isOpen == YES) {
        [self.dataBase deleteDataWithModel:_model];
        [btn setImage:[UIImage imageNamed:@"nocollect.png"] forState:UIControlStateNormal];
        btn.tintColor = [UIColor whiteColor];
        _hub.labelText = @"删除成功";
        _isOpen = NO;
    }else
    {
        if (_model.cityID == nil) {
            _hub.labelText = @"未加载完成哦";
        }
        else{
            [self.dataBase insertDataWithModel:_model];
            [btn setImage:[UIImage imageNamed:@"collected.png"] forState:UIControlStateNormal];
            btn.tintColor = [UIColor redColor];
            _hub.labelText = @"收藏成功";
            _isOpen = YES;
        }
    }
    [self.view addSubview:_hub];
    [_hub showAnimated:NO whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [_hub removeFromSuperview];
    }];
}

- (UILabel *)prompt
{
    if (!_prompt) {
        self.prompt = [[UILabel alloc]init];
        _prompt.numberOfLines = 0;
        _prompt.font = [UIFont systemFontOfSize:13];
        _prompt.textColor = [UIColor grayColor];
    }
    return _prompt;
}

// 返回
- (void)backToPage
{
    [self dismissViewControllerAnimated:YES completion:^{
    
    }];
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.itemSize = CGSizeMake(ScreenWidth / 2 - 5, ScreenWidth / 3 );
        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flow.minimumInteritemSpacing = 5;
        flow.minimumLineSpacing = 5;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.rect.size.height, ScreenWidth, ScreenWidth / 3) collectionViewLayout:flow];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[CityintroductCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
        [self.scroller addSubview:self.collectionView];
    }
    return _collectionView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.model.pics.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CityintroductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.url = self.model.pics[indexPath.row];
    return cell;
}

// 城市介绍
- (UILabel *)desc
{
    if (!_desc) {
        _desc = [[UILabel alloc]init];
        _desc.numberOfLines = 0;
        _desc.font = [UIFont systemFontOfSize:13];
        _desc.textColor = [UIColor grayColor];
    }
    return _desc;
}

// 城市图片
- (UIImageView *)headerImg
{
    if (!_headerImg) {
        self.headerImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, -ScreenWidth / 3 * 2, ScreenWidth, ScreenWidth / 3 * 2)];
        self.headerImg.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _headerImg;
}

// 放置lable imageview
- (UIScrollView *)scroller
{
    if (!_scroller) {
        _scroller = [[UIScrollView alloc]initWithFrame:self.view.bounds];
        _scroller.contentSize = CGSizeMake(0, ScreenHeight * 2 - 300);
        _scroller.contentInset = UIEdgeInsetsMake(ScreenWidth / 3 * 2, 0, 0, 0);
        _scroller.contentOffset = CGPointMake(0, -ScreenWidth / 3 * 2);
        _scroller.showsVerticalScrollIndicator = NO;
        _scroller.delegate = self;
    }
    return _scroller;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    if (y < - ScreenWidth / 3 * 2) {
        CGRect frame = self.headerImg.frame;
        frame.origin.y = y;
        frame.size.height =  -y;
        self.headerImg.frame = frame;
    }
}

- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://api.mxtrip.cn/api/area/getCityDetail?cityid=%@&_tk=1446255813:5975&apiVersion=1.1&clientVersion=1.2.0&idfa=A857AE53-A1D1-4331-9E4E-62937AB3C688",self.cityID];
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        self.model = [MainIntroductionModel modelWithDic:dataDic];
        self.model.cityID = self.cityID;
        self.model.name = self.name;
        [self.headerImg sd_setImageWithURL:[NSURL URLWithString:self.model.mainpic] placeholderImage:[UIImage imageNamed:@"chartlet_image_traning@2x.png"]];
        self.rect = [self.model.brief boundingRectWithSize:CGSizeMake(ScreenWidth, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
        _desc.frame = CGRectMake(10, 40, ScreenWidth - 20, _rect.size.height);
        _collectionView.frame = CGRectMake(0, _rect.size.height + 50, ScreenWidth, ScreenWidth / 3);
        UILabel *idea = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth / 2 - 50, _rect.size.height + 60 + ScreenWidth / 3, 100, 30)];
        idea.textAlignment = NSTextAlignmentCenter;
        idea.text = @"小贴士";
        [self.scroller addSubview:idea];
        CGRect rect = [self.model.tips boundingRectWithSize:CGSizeMake(ScreenWidth, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
        _prompt.frame = CGRectMake(10, _rect.size.height + 60 + ScreenWidth / 3 + 30, ScreenWidth - 20, rect.size.height + 100);
        _prompt.text = [NSString stringWithFormat:@"%@\n\n风俗禁忌:\n%@",self.model.tips,self.model.customs];
        _desc.text = self.model.brief;
        [self.collectionView reloadData];
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.collectionView.delegate = nil;
    self.collectionView.dataSource = nil;
    [self.dataBase close];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.dataBase open];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
